package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.anno.EmpLoginLogOperation;
import com.itheima.anno.LogOperation;
import com.itheima.anno.MyLog;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprService empExprService;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;
    @Lazy
    @Autowired
    private DeptService deptService;

    /*mybatis-plus*/
    //分页查询
    @Override
    public EmpResult pageEmp(EmpQueryParam queryParam) {
        //1.定义条件
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(queryParam.getName() != null && !queryParam.getName().isEmpty(),Emp::getName,queryParam.getName())
                .eq(queryParam.getGender() != null,Emp::getGender,queryParam.getGender())
                .between(queryParam.getBegin() != null && queryParam.getEnd() != null,Emp::getEntryDate,queryParam.getBegin(),queryParam.getEnd());
        //2.分页查询
        //2.1获取分页数据
        Page<Emp> page = Page.of(queryParam.getPage(),queryParam.getPageSize());

        //2.2带条件查询
        Page<Emp> p = this.page(page,queryWrapper);
        List<Emp> records = p.getRecords();
        //查询records中所有部门id
        List<Integer> deptIds = records.stream().map(Emp::getDeptId).toList();

        //遍历records，封装部门名称
        if(!deptIds.isEmpty()){
            List<Dept> depts = deptService.listByIds(deptIds);
            records.forEach(emp->{
                depts.forEach(dept->{
                    if(emp.getDeptId()!=null && emp.getDeptId().equals(dept.getId()))
                        emp.setDeptName(dept.getName());
                });
            });
        }

        return new EmpResult(p.getTotal(),records);
    }

    //新增员工
    @Override
    @Transactional
    public void insertEmp(Emp emp) {
        //1.添加员工基本信息
        this.save(emp);
        //2.添加员工工作经历
        //2.1 为员工经历存入员工id
        emp.getExprList().forEach(expr ->expr.setEmpId(emp.getId()));
        //2.2 工作经历不为空则批量存入
        if(emp.getExprList() != null && !emp.getExprList().isEmpty()){
            empExprService.saveBatch(emp.getExprList());
        }
    }

    //删除员工
    @Override
    @Transactional
    public void deleteEmp(List<Integer> ids) {
        //1.先删除员工的工作经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId,ids));
        //2.删除员工基本信息
        empExprService.removeByIds(ids);
    }

    //查询回显
    @Override
    public Emp getEmpById(Integer id) {
        //1.查询员工表
        Emp emp = this.getById(id);

        //2.查询工作经历并封装到emp对象中
        emp.setExprList(empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId,id)));
        return emp;
    }

    //修改员工
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        //1.更新员工基本信息
        this.updateById(emp);
        //2.删除员工原来的工作经历
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId,emp.getId()));
        //3.批量保存员工工作经历
        if(emp.getExprList()!=  null && !emp.getExprList().isEmpty()){
            emp.getExprList().forEach(expr ->expr.setEmpId(emp.getId()));
        }
        empExprService.saveBatch(emp.getExprList());
    }


    /*mybatis*/
/*    //分页查询
    @Override
    @LogOperation
    public EmpResult page(EmpQueryParam queryParam) {
        return null;
    }

    //添加员工
    @Transactional(rollbackFor = Exception.class)
    @Override
    @LogOperation
    public void addEmp(Emp emp) {
        try {
            //1.填补基础信息
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            //2.保存员工基本信息
            empMapper.addMapperEmp(emp);
            //3.批量保存员工的工作经历
            Integer id = emp.getId();//员工id
            List<EmpExpr> exprList = emp.getExprList();
            if (exprList != null && !exprList.isEmpty()){
                //遍历exprList，将员工的id设置到exprList中
                exprList.forEach(expr ->expr.setEmpId(id));
                //调用exprMapper的方法批量保存工作经历
                empExprMapper.addMapperEmpExpr(exprList);
            }
        } finally {
            EmpLog empLog = new EmpLog(emp.getId(), LocalDateTime.now(), "新增员工" + emp.getName());
            empLogService.insertLog(empLog);
        }

    }

    //查询全部员工
    @LogOperation
    @Override
    public List<Emp> getAllEmp() {
        log.info("查询全部员工");
        return empMapper.getMapperAllEmp();
    }

    //删除员工(可批量)
    @LogOperation
    @MyLog
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<Integer> ids) {
        //1.先删除员工的工作经历
        try {
            empExprMapper.deleteByIds(ids);
        }finally {
            //3.记录日志
            ids.forEach(id -> {
                EmpLog empLog = new EmpLog(id, LocalDateTime.now(), "删除员工" + id);
                empLogService.insertLog(empLog);
            });
        }
        //2.删除员工的基本信息
        empMapper.deleteByIds(ids);
    }


    //查询回显（根据id查询员工）
    @LogOperation
    @Override
    public Emp getEmpById(Integer id) {
        //先查询工作经历封装到exprList对象中
        List<EmpExpr> exprById = empExprMapper.getExprById(id);
        //查询员工基本信息
        Emp emp = empMapper.getEmpById(id);
        emp.setExprList(exprById);
        return emp;
    }

    //修改员工
    @LogOperation
    @Override
    public void updateEmp(Emp emp) {
        //填补更新时间
        emp.setUpdateTime(LocalDateTime.now());
        //修改员工工作经历(先删除再新增)
        empExprMapper.deleteByIds(List.of(emp.getId()));
        //判断exprList是否为空
        if (emp.getExprList() != null && !emp.getExprList().isEmpty()){
            //先存id
            emp.getExprList().forEach(expr ->expr.setEmpId(emp.getId()));
            empExprMapper.addMapperEmpExpr(emp.getExprList());
        }
        //修改员工基本信息
        empMapper.updateEmp(emp);
    }*/

    //登录认证
    @Override
    @Transactional
    public LoginInfo login(Emp emp) {
        Emp empLogin = empMapper.getUsernameAndPassword(emp);
        if(empLogin != null){
            //生成令牌
            Map<String,Object> claims = new HashMap();
            claims.put("id",empLogin.getId());
            claims.put("username",empLogin.getUsername());
            String token = JwtUtils.generateJwt(claims);
            return new LoginInfo(empLogin.getId(),empLogin.getUsername(),empLogin.getName(),token);
        }
        return null;
    }


}
